/**
 * Copyright &copy; 2019-2022 <a href="https://gitee.com/rit/zx-pm">zx-pm</a> All rights reserved.
 */
package com.zx.pm.modules.zx.web;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.zx.pm.common.beanvalidator.BeanValidators;
import com.zx.pm.common.config.Global;
import com.zx.pm.common.persistence.Page;
import com.zx.pm.common.utils.StringUtils;
import com.zx.pm.common.utils.excel.ImportExcel;
import com.zx.pm.common.web.BaseController;
import com.zx.pm.modules.sys.utils.UserUtils;
import com.zx.pm.modules.zx.entity.Lzd;
import com.zx.pm.modules.zx.entity.TenderRequire;
import com.zx.pm.modules.zx.entity.YwLog;
import com.zx.pm.modules.zx.service.LzdService;
import com.zx.pm.modules.zx.service.TenderRequireService;
import com.zx.pm.modules.zx.service.TenderSectionService;
import com.zx.pm.modules.zx.service.YwLogService;

/**
 * 项目流转单Controller
 * @author forest
 * @version 2019-01-06
 */
@Controller
@RequestMapping(value = "${adminPath}/zx/lzd")
public class LzdController extends BaseController {

	@Autowired
	private LzdService lzdService;
	
	@Autowired
	private YwLogService ywLogService;
	
	@Autowired
	private TenderRequireService tenderRequireService;
	
	@Autowired
	private TenderSectionService tenderSectionService;
	
	@ModelAttribute
	public Lzd get(@RequestParam(required=false) String id) {
		Lzd entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = lzdService.get(id);
			String str = entity.getDemonstration();
			if(StringUtils.isNotBlank(str)) {
				entity.setDemonstrationArray(str.split(","));
			}
			entity.settRequire(tenderRequireService.getByLzdId(id));
		}
		if (entity == null){
			entity = new Lzd();
		}
		return entity;
	}
	
	@RequiresPermissions("zx:lzd:view")
	@RequestMapping(value = {"list", ""})
	public String list(Lzd lzd, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Lzd> page = lzdService.findPage(new Page<Lzd>(request, response), lzd); 
		model.addAttribute("page", page);
		
		model.addAttribute("currentUser", UserUtils.getUser());
		return "modules/zx/lzdList";
	}


	@RequiresPermissions("zx:lzd:view")
	@RequestMapping(value = "show")
	public String show(Lzd lzd, Model model) {
		List<String> list = lzdService.getBuyUnitList();
		StringBuffer sb = new StringBuffer();
		sb.append("[");
		if(list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				if(i == 0){
					sb.append("'").append(list.get(i)).append("'");
				}else{
					sb.append(",").append("'").append(list.get(i)).append("'");
				}
			}
		}
		sb.append("]");
		// 获取项目标段信息
		lzd.setSectionList(tenderSectionService.getSectionListByLzdId(lzd.getId(), null));
		model.addAttribute("lzd", lzd);
		model.addAttribute("buyUnitList", sb.toString());
		//保存业务操作日志
		if(StringUtils.isNotBlank(lzd.getId())) {
			YwLog yw = new YwLog();
			yw.setType("3");
			yw.setDataId(lzd.getId());
			yw.setYwTable("zx_lzd");
			yw.setYwName("项目基本信息");
			yw.setRemoteAddr("0:0:0:0:0:0:0:1");
			ywLogService.save(yw);
		}
		
		return "modules/zx/lzdShow";
	}
	
	@RequestMapping(value = "restartForm")
	public String restartForm(Lzd lzd, Model model) {
		List<String> list = lzdService.getBuyUnitList();
		StringBuffer sb = new StringBuffer();
		sb.append("[");
		if(list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				if(i == 0){
					sb.append("'").append(list.get(i)).append("'");
				}else{
					sb.append(",").append("'").append(list.get(i)).append("'");
				}
			}
		}
		sb.append("]");
		if("1".equals(lzd.getIsSubpackage())) {
			// 获取子标段
			lzd.setSectionList(tenderSectionService.getSectionListByLzdId(lzd.getId(), "1"));
		}
		model.addAttribute("lzd", lzd);
		model.addAttribute("buyUnitList", sb.toString());
		
		return "modules/zx/restartlzdForm";
	}
	
	@RequiresPermissions("zx:lzd:view")
	@RequestMapping(value = "form")
	public String form(Lzd lzd, Model model) {
		List<String> list = lzdService.getBuyUnitList();
		StringBuffer sb = new StringBuffer();
		sb.append("[");
		if(list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				if(i == 0){
					sb.append("'").append(list.get(i)).append("'");
				}else{
					sb.append(",").append("'").append(list.get(i)).append("'");
				}
			}
		}
		sb.append("]");
		if("1".equals(lzd.getIsSubpackage())) {
			// 获取子标段
			lzd.setSectionList(tenderSectionService.getSectionListByLzdId(lzd.getId(), null));
		}
		
		model.addAttribute("lzd", lzd);
		model.addAttribute("buyUnitList", sb.toString());
		//保存业务操作日志
		if(StringUtils.isNotBlank(lzd.getId())) {
			YwLog yw = new YwLog();
			yw.setType("3");
			yw.setDataId(lzd.getId());
			yw.setYwTable("zx_lzd");
			yw.setYwName("项目基本信息");
			yw.setRemoteAddr("0:0:0:0:0:0:0:1");
			ywLogService.save(yw);
		}
		
		return "modules/zx/lzdForm";
	}

	@RequiresPermissions("zx:lzd:edit")
	@RequestMapping(value = "save")
	public String save(Lzd lzd, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model,  lzd)){
			return form(lzd, model);
		}
		
		if (lzd.getIsNewRecord()){
			lzd.setOperateFalg("1");
			// 项目处于填写基本信息阶段
			lzd.setLzdStatus("1");
			lzd.preInsert();
		}else {
			lzd.setOperateFalg("2");
			lzd.preUpdate();
		}
		TenderRequire tr = new TenderRequire();
		tr = lzd.gettRequire();
		// 设置流转单ID
		tr.setLzdId(lzd.getId());
		if("1".equals(lzd.gettRequire().getSpecialRequire())) {
			lzd.gettRequire().setRequireContent("");
		}
		if(lzd.getDemonstrationArray().length > 0) {
			lzd.setDemonstration(StringUtils.join(lzd.getDemonstrationArray(), ","));
		}
		lzdService.save(lzd);
		tenderRequireService.save(tr);
		addMessage(redirectAttributes, "保存项目信息成功");
		return "redirect:"+Global.getAdminPath()+"/zx/lzd/list?repage";
	}
	
	@RequiresPermissions("zx:lzd:edit")
	@RequestMapping(value = "delete")
	public String delete(Lzd lzd, RedirectAttributes redirectAttributes) {
		lzdService.delete(lzd);
		// 删除该项目下的所有子标段
		tenderSectionService.delBylzdId(lzd.getId());
		addMessage(redirectAttributes, "删除项目信息成功");
		return "redirect:"+Global.getAdminPath()+"/zx/lzd/?repage";
	}

	@ResponseBody
	@RequestMapping(value = "getByBuyUnit", method = RequestMethod.GET)
	public TenderRequire getByBuyUnit(HttpServletRequest request) {
		Lzd lzd = new Lzd();
		lzd.setBuyUnit(request.getParameter("name"));
		lzd = lzdService.getByBuyUnit(lzd);
		TenderRequire tr = tenderRequireService.getByLzdId(lzd.getId());
		return tr;
	}
	
	@RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Lzd> list = ei.getDataList(Lzd.class);
			for (Lzd l : list){
				try{
					l.setOperateFalg("1");
					l.setLzdStatus("1");
					l.preInsert();
					l.setIsSubpackage("2");
					TenderRequire tr = new TenderRequire();
					// 设置流转单ID
					tr.setLzdId(l.getId());					
					tr.setBuyerPhone(l.getExBuyerPhone());
					tr.setContact(l.getExContact());
					tr.setProEndDate(l.getExProEndDate());
					tr.setZbArray(new String[0]);
					tenderRequireService.save(tr);
					lzdService.save(l);
					// 保存信息至数据库
					successNum++;
					
				}catch(ConstraintViolationException ex){
					failureMsg.append("<br/>项目信息 "+l+" 导入失败：");
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList){
						failureMsg.append(message+"; ");
						failureNum++;
					}
				}catch (Exception ex) {
					ex.printStackTrace();
					failureMsg.append("<br/>项目 "+l.getProName()+" 导入失败："+ex.getMessage());
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条项目信息，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条项目信息"+failureMsg);
		} catch (Exception e) {
			e.printStackTrace();
			addMessage(redirectAttributes, "导入信息失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/zx/lzd/?repage";
    }
	
	@RequestMapping(value = "import/template",method = RequestMethod.GET)
    public void importFileTemplate(HttpServletResponse response, HttpServletRequest request, RedirectAttributes redirectAttributes) {
		/*try {
            String fileName = "项目基本信息数据导入模板.xlsx";
    		List<Lzd> list = Lists.newArrayList();
    		new ExportExcel("项目信息", Lzd.class, 2).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}*/
		OutputStream outp = null;
        FileInputStream in = null;
        String templeteName = "项目基本信息数据导入模板.xlsx";
        try {
            String fileName = templeteName; //要下载的模板文件
            if(templeteName!=null){
                if(!templeteName.endsWith(".xlsx")){
                    fileName = templeteName + ".xlsx";
                }
            }
           
            String ctxPath = getClass().getResource("/templates/excel/" + fileName).getPath();

            String filedownload = ctxPath;
            fileName = URLEncoder.encode(fileName, "UTF-8");
            // 要下载的模板所在的绝对路径
            response.reset();
            response.addHeader("Content-Disposition", "attachment; filename="+fileName);
            response.setContentType("application/octet-stream;charset=UTF-8");
            outp = response.getOutputStream();
            in = new FileInputStream(filedownload);
            byte[] b = new byte[1024];
            int i = 0;
            while ((i = in.read(b)) > 0) {
                outp.write(b, 0, i);
            }
            outp.flush();
        } catch (Exception e) {
            System.out.println("Error!");
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
                in = null;
            }
            if (outp != null) {
                try {
					outp.close();
				} catch (IOException e) {			
					e.printStackTrace();
				}
                outp = null;
            }
        }

    }
}